<?
class Mailing_model extends CI_Model
{
	function __construct()
	{
		parent::__construct();
	}

	function getTemplates()
	{
		return $this->db->get('mail_template')->result();
	}

	function getMailings()
	{
		return $this->db->where('dDeleted', 0)->get('mailing')->result();
	}

	function getMailing($id)
	{
		return $this->db->where('id', abs($id))->get('mailing')->row();
	}

	function saveMailing($data)
	{
		if (empty($data['pTitle']) || empty($data['pText']))
			return false;

		$upd = array(
			'pTitle' => $data['pTitle'],
			'pText' => $data['pText'],
		);

		if (!empty($data['pRecipient']))
		{
			$upd['pRecipient'] = join('', array_keys($data['pRecipient']));
		}

		if (empty($data['id']))
		{
			$upd['dCreated'] = now();
			$upd['tUserCreated'] = $this->user->id;
			$this->db->insert('mailing', $upd);
			return $this->db->insert_id();
		}
		else
		{
			$upd['dUpdated'] = now();
			$upd['tUserUpdated'] = $this->user->id;
			$this->db->where('id', abs($data['id']))->update('mailing', $upd);
			return abs($data['id']);
		}
	}

	function addSubscribes($list = '')
	{
		$this->load->helper('email_helper');
		$list = explode(',', $list);
		$emails = array();
		foreach ($list as $val)
		{
			if (valid_email($val = trim($val)))
				$emails[]=$val;
		}

		if (empty($emails))
			return false;
		
		$res = extractFieldFromDataArray($this->db->where_in('pEmail', $emails)->get('mail_subscriber')->result(), 'pEmail');
		$emails = array_diff($emails, $res);

		$res = extractFieldFromDataArray($this->db->where_in('pEmail', $emails)->get('user')->result(), 'pEmail');
		$emails = array_diff($emails, $res);

		if (empty($emails))
			return false;

		$list = array();
		foreach ($emails as $email)
		{
			$list[]=array(
				'pEmail' => $email,
				'pKey' => md5(uniqid())
			);
		}

		return $this->db->insert_batch('mail_subscriber', $list);
	}

	function getSubscribes()
	{
		return $this->db->get('mail_subscriber')->result();
	}

	function setMailing($id = 0, $withIgnore = false)
	{
		$res = $this->db->where(
			array(
				'id' => $id = abs($id),
				'dDeleted' => 0
			)
		)->get('mailing')->row();
		
		if (empty($res))
			return false;

		if ($res->pRecipient == '')
			return array('error' => 'Нет получателей');

		$ignoreList = array(
			0 => array(),
			1 => array(),
		);

		if ($withIgnore)
		{
			$available = $this->db->where('tMailing', $id)->get('mail_sent')->result();
			foreach ($available as $val)
				$ignoreList[$val->pSenderType][]=$val->tSender;
		}

		$emails = array();
		$ins = array();
		
		if (strpos($res->pRecipient, '0') !== false)
		{
			if (!empty($ignoreList[0]))
				$this->db->where_not_in('id', $ignoreList[0]);
			$recs = $this->db->select('id, pEmail, pKey')->where('pSubscribed', 1)->get('user')->result();
			$emails = extractFieldFromDataArray($recs, 'pEmail');

			if (!empty($recs))
			{
				foreach ($recs as $val)
				{
					$ins[]=array(
						'tMailing' => $id,
						'pSenderType' => 0,
						//'pEmail' => $val->pEmail,
						'tSender' => $val->id
					);
				}
			}
		}

		if (strpos($res->pRecipient, '1') !== false)
		{
			if (!empty($ignoreList[1]))
				$this->db->where_not_in('id', $ignoreList[1]);
			$recs = $this->db->select('id, pEmail, pKey')->where('pSubscribed', 1)->get('mail_subscriber')->result();
			// $emails = array_merge(extractFieldFromDataArray($recs, 'pEmail'), $emails);

			if (!empty($recs))
			{
				foreach ($recs as $val)
				{
					if (in_array($val->pEmail, $emails))
						continue;
					$ins[]=array(
						'tMailing' => $id,
						'pSenderType' => 1,
						//'pEmail' => $val->pEmail,
						'tSender' => $val->id
					);
				}
			}
		}
		
		if (empty($ins))
			return array('error' => 'Нет получателей');

		if ($this->db->insert_batch('mail_sent', $ins))
			return array(
				'all' => count($ins)
			);
		else
			return array('error' => 'Ошибка БД');
	}

	function checkMailing($id = 0)
	{
		if (!($recs = $this->db->where('tMailing', abs($id))->count_all_results('mail_sent')))
			return false;
		else
		{
			return array(
				'all' => $recs,
				'cnt' => $this->db->where('tMailing', abs($id))->where('dSending >', 0)->count_all_results('mail_sent')
			);
		}
	}

	function sendMoreMailing($id = 0)
	{
		$this->email_model->sendQueue();

		$res = $this->db->where(array(
			'dSending' => 0,
			'tMailing' => abs($id),
		))->get('mail_sent', 1)->row();

		if ($res)
		{
			$this->load->model('email_model');

			// Проверка ограничений
			if (!$this->email_model->checkLimits())
				return array('message' => 'limit');

			// dieJSON($res);
			if ($res->pSenderType == '1')
			{
				$man = $this->db->where(array(
					'id' => $res->tSender,
					'pSubscribed' => 1
				))->get('mail_subscriber')->row();
			}
			else
			{
				$man = $this->db->where(array(
					'id' => $res->tSender,
					'pSubscribed' => 1
				))->get('user')->row();
			}

			if (empty($man))
			{
				$sending = false;
				$email = $res->tSender.' - отписан';
			}
			else
			{
				$mailing = $this->getMailing($res->tMailing);

				$mailing->pText = str_replace('*unlink*', base_url().'link/unsubscribe/'.$man->id.'/'.$res->pSenderType.'/'.md5($man->id.$man->pKey), $mailing->pText);

				$sending = $this->email_model->sendEmail($man->pEmail, $mailing->pTitle, $mailing->pText, false);
				// $sending = 1;
				$email = $man->pEmail;
			}
			
			$this->db->where('id', $res->id)->update('mail_sent', array('dSending' => now(), 'pStatus' => $sending?1:0));
			
			return array(
				'email' => $email,
				'status' => $sending,
				'cnt' => $this->db->where('tMailing', abs($id))->where('dSending >', 0)->count_all_results('mail_sent')
			);
		}
		else
		{
			return array('message' => 'done');
		}
	}

	function unsubscribe($uid = false, $type = false, $hash = false)
	{
		
		$table = ($type == 1)?'mail_subscriber':'user';
		
		$man = $this->db->where(array(
			'id' => $uid,
			'pSubscribed' => 1
		))->get($table)->row();

		if (empty($man))
			return true;

		if ($hash !== md5($uid.$man->pKey))
			return false;
		else
			return $this->db->where(array(
				'id' => $uid
			))->update($table, array('pSubscribed' => 0));
	}
}
?>